#region MIT Licence
/*
 * Copyright (C) 2014 PdfCreative
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom 
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;

using PdfCreative.Pdf;
using PdfCreative.Pdf.Writer;


namespace PdfCreative.Pdf.Graphics
{
    /// <summary>
    /// The GraphicsState class maintains a number of properties that collectively make up a graphical state.
    /// The GraphicsState is updated when text or shapes are being drawn, and used to determine if state-changing
    /// commands need to be sent out to the target page.
    /// </summary>
    internal class GraphicsState : ICloneable
    {
        // Private fields
        // ==============
        #region Private fields
        private Brush _brush;
        private Matrix _coordinateSpace;
        private float _currentXCoordinate;
        private float _currentYCoordinate;
        private StringFormat _format;
        private bool _hasCurrentPoint;
        private Pen _pen;
        private PdfWriter _writer;
        #endregion



        // Public properties
        // =================
        #region Public properties
        /// <summary>
        /// Retrieves the currently active coordinate space.
        /// </summary>
        public Matrix CoordinateSpace
        {
            get { return _coordinateSpace; }
        }
        #endregion



        // Public methods
        // ==============
        #region Public methods
        /// <summary>
        /// Indicates if the specified coordinates are the same as the current point.
        /// </summary>
        /// <param name="x">The X coordinate</param>
        /// <param name="y">The Y coordinate</param>
        /// <returns>A boolean value indicating if the points are the same (true) or not.</returns>
        public bool IsCurrentPoint(float x, float y)
        {
            return _hasCurrentPoint && (x == _currentXCoordinate) && (y == _currentYCoordinate);
        }

        /// <summary>
        /// Updates the current point for path construction operations.
        /// </summary>
        /// <param name="x">The X coordinate</param>
        /// <param name="y">The Y coordinate</param>
        public void SetCurrentPoint(float x, float y)
        {
            _hasCurrentPoint = true;
            _currentXCoordinate = x;
            _currentYCoordinate = y;
        }

        /// <summary>
        /// Unsets the current point.
        /// </summary>
        public void UnsetCurrentPoint()
        {
            _hasCurrentPoint = false;
        }

        /// <summary>
        /// Updates the GraphicsState with the specified coordinate space matrix.
        /// </summary>
        /// <param name="coordinateSpace">The new coordinate space.</param>
        public void Update(Matrix coordinateSpace)
        {
            _coordinateSpace = coordinateSpace;
        }

        /// <summary>
        /// Updates the GraphicsState with the specified pen.
        /// </summary>
        /// <param name="pen">The pen</param>
        public void Update(Pen pen)
        {
            System.Diagnostics.Debug.Assert(null != pen);

            if (false == pen.Equals(_pen))
            {
                pen.WriteChanges(_writer, _pen);
                _pen = pen.Clone();
            }
        }

        /// <summary>
        /// Updates the GraphicsState with the specified brush.
        /// </summary>
        /// <param name="brush">The brush</param>
        public void Update(Brush brush)
        {
            System.Diagnostics.Debug.Assert(null != brush);
        
            // If this brush is a resource brush we output the resource, otherwise we output the properties of the brush that are
            // different from the current graphics state.
            if (false == brush.Equals(_brush))
            {
                brush.WriteChanges(_writer, _brush);
                _brush = brush.Clone();
            }
        }

        /// <summary>
        /// Updates the GraphicsState with the specified brush and resource reference.
        /// </summary>
        /// <param name="brush">The brush</param>
        /// <param name="resource">The resource reference</param>
        public void Update(Brush brush, PdfResourceReference resource)
        {
            brush.WriteResource(_writer, resource);
            _brush = null;  // force the next brush to be output
        }

        /// <summary>
        /// Updates the GraphicsState with the specified string format.
        /// </summary>
        /// <param name="format">The string format.</param>
        public void Update(StringFormat format)
        {
            format.WriteChanges(_writer, _format);
            _format = format.Clone();

        }

        #endregion



        // Interface implementations
        // =========================
        #region ICloneable Members
        /// <summary>
        /// Creates a clone of the current GraphicsState instance and returns the cloned instance.
        /// </summary>
        /// <returns>The cloned instance</returns>
        public object Clone()
        {
            GraphicsState clone = new GraphicsState(_writer);
            clone._brush = this._brush.Clone();
            clone._pen = this._pen.Clone();
            clone._coordinateSpace = (Matrix) this._coordinateSpace.Clone();
            clone._currentXCoordinate = this._currentXCoordinate;
            clone._currentYCoordinate = this._currentYCoordinate;
            clone._format = this._format.Clone();
            clone._hasCurrentPoint = this._hasCurrentPoint;
            clone._writer = this._writer;
            return clone;
        }  
        #endregion


        
        // Public constructor
        // ==================
        #region Public constructor
        /// <summary>
        /// Constructs a new GraphicsState instance.
        /// </summary>
        public GraphicsState(PdfWriter writer)
        {
            // The initial coordinate space is represented by the identity matrix.
            _coordinateSpace = new Matrix(3,3);
            _coordinateSpace.SetIdentityValues();

            _brush = new SolidBrush(new RgbColour(0,0,0));
            _format = new StringFormat();
            _pen = new Pen(new RgbColour(0,0,0));
            _writer = writer;
        }
        #endregion

    } // GraphicsState class
}
